<?php
/**
 * Created by PhpStorm.
 * User: crystal
 * Date: 2017/9/8
 * Time: 15:52
 */

namespace lib;

/**
 * 应用程序容器（简单的对象工厂）
 *
 * Class Application
 * @package lib
 */
class Application
{
    private static $instance = null;

    private $classBindings = [];
    //private $instances = [];

    private function __construct()
    {
        //
    }

    /**
     * 获取Application类的唯一实例
     *
     * @return Application
     */
    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new Application();
        }
        return self::$instance;
    }

    /**
     * 将具体的实现类，或子类与父类（抽象类）与接口绑定
     *
     * @param $abstract
     * @param $implement
     */
    public function bind($abstract, $implement)
    {
        $this->classBindings[$abstract] = $implement;
    }

    /**
     * 从容器(对象工厂)当中得到对象实例
     *
     * @param $type
     * @param $directory
     * @return JsonFileAccess|SerializeFileAccess
     */
    public function getObject($abstract)
    {
        if (isset($this->classBindings[$abstract]) && !empty($this->classBindings[$abstract])) {
            $implements = $this->classBindings[$abstract];
            $obj = $this->createObject($implements);
            return $obj;
        }
        return null;
    }

    /**
     * 创建子类的实例对象
     *
     * @param $implementClass string 指定的子类名称
     * @return null|object
     */
    private function createObject($implementClass)
    {
        if (class_exists($implementClass)) {
            $reflectionClass = new \ReflectionClass($implementClass);
            return $reflectionClass->newInstance();
        }
        return null;
    }
}